package com.dhcc.bpm.modules.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.constant.FilePathConstant;
import com.dhcc.bpm.modules.api.entity.Api;
import com.dhcc.bpm.modules.api.mapper.ApiMapper;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.vo.ApiListVo;
import com.dhcc.bpm.modules.api.vo.ApiPageVO;
import com.dhcc.bpm.modules.api.vo.ApiVO;
import com.dhcc.bpm.modules.api.vo.ListAllApisVO;
import com.dhcc.bpm.modules.common.vo.SelectVo;
import com.dhcc.bpm.modules.log.vo.AppApiViewVo;
import com.dhcc.bpm.modules.system.entity.Param;
import com.dhcc.bpm.modules.system.service.impl.ParamServiceImpl;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import javax.validation.constraints.NotEmpty;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ApiServiceImpl
 * @Description api表 服务实现类
 * @Author daina
 * @Date 2020/2/25 15:22
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@Service("opc_api")
public class ApiServiceImpl extends BaseServiceImpl<ApiMapper, Api> implements IApiService {

    @Autowired
    private ApiMapper apiMapper;
    @Autowired
    private ParamServiceImpl ParamService;
    @Autowired
    private FastFileStorageClient storageClient;

    private String openApiPath;

    @Value("${bpm.file-public-path}")
    public void setFileUploadPath(String publicPath) {
        openApiPath = publicPath + FilePathConstant.OPENAPIPATH;
    }

    @Override
    public IPage<ApiVO> listInfo(IPage<ApiVO> page, ApiVO api) {
        if (api.getStartDate() != null) {
            api.setStartDate(api.getStartDate().substring(0, 10));
        }
        if (api.getEndDate() != null) {
            api.setEndDate(api.getEndDate().substring(0, 10));
        }
        return page.setRecords(apiMapper.listInfo(page, api));
    }

    @Override
    public List<ApiVO> selectApiList(ApiVO api) {
        return apiMapper.selectApiList(api);
    }

    @Override
    public IPage<ApiVO> listByProductId(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(apiMapper.listByProductId(page, api));
    }

    @Override
    public List<SelectVo> selectApiName() {
        return apiMapper.selectApiName();
    }

    @Override
    public IPage<ApiVO> selectApiPage(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(baseMapper.selectApiPage(page, api));
    }

    @Override
    public IPage<ApiVO> ByProductId(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(apiMapper.selectByProductId(page, api));
    }

    @Override
    public IPage<ApiVO> getApiByProductId(IPage<ApiVO> page, ApiVO apivo) {
        return page.setRecords(apiMapper.getApiByProductId(page, apivo));
    }

    @Override
    public IPage<ApiVO> getApiByAppId(IPage page, ApiVO apivo) {
        return page.setRecords(apiMapper.getApiByAppId(page, apivo));
    }

    @Override
    public List<ApiVO> listByBackserviceId(Long backserviceId) {
        return apiMapper.listByBackserviceId(backserviceId);
    }

    @Override
    public IPage<ApiVO> getCostApiByProductId(IPage<ApiVO> page, ApiVO apivo) {
        return page.setRecords(apiMapper.getCostApiByProductId(page, apivo));
    }

    @Override
    public IPage<ApiVO> selectControllerPage(IPage<ApiVO> page, ApiVO api) {
        return apiMapper.selectControllerPage(page, api);
    }

    @Override
    public IPage<ApiVO> selectUnControllerApiList(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(baseMapper.selectUnControllerApiList(page, api));
    }

    @Override
    public IPage<ApiVO> selectProductApiList(IPage<ApiVO> page, ApiVO api) {
        return apiMapper.selectProductApiList(page, api);
    }

    @Override
    public IPage<ApiVO> selectBaseProductApiList(IPage<ApiVO> page, ApiVO api) {
        return apiMapper.selectBaseProductApiList(page, api);
    }

    @Override
    public IPage<ApiVO> selectSysApiList(IPage<ApiVO> page, ApiVO api) {
        return apiMapper.selectSysApiList(page, api);
    }

    @Override
    public IPage<AppApiViewVo> selectAppApiList(IPage<AppApiViewVo> page, AppApiViewVo appApiVO) {
        return apiMapper.selectAppApiList(page, appApiVO);
    }

    @Override
    public String saveOpenapi(String apiCode, Map maps) throws IOException {
        // 获取上传文件类型
        Param param = ParamService.getParamByKey("bpm.fileUploadType");
        String paramValue = param.getParamValue();
        File path = new File(openApiPath + "/" + apiCode + "/");
        if (!path.exists()) {
            path.mkdirs();
        }
        try (RandomAccessFile br = new RandomAccessFile(openApiPath + "/" + apiCode + "/openApi3.yaml", "rw")) {
            Yaml yaml = new Yaml();
            br.write(yaml.dumpAsMap(maps).trim().getBytes());
            if ("1".equals(paramValue)) {
                return openApiPath + "/" + apiCode + "/openApi3.yaml";
            } else {
                try (InputStream inputStream = new FileInputStream(openApiPath + "/" + apiCode + "/openApi3.yaml")) {
                    int fileLength = inputStream.available();//获取文件大小
                    StorePath storePath = storageClient.uploadFile(inputStream, fileLength, FilenameUtils.getExtension("openApi3.yaml"), null);
                    inputStream.close();
                    //删除服务器本地文件
                    delete(path);
                    return storePath.getGroup() + "/" + storePath.getPath();
                } catch (IOException e) {
                    log.error("异常信息:{}", e);
                }
            }
        } catch (IOException e) {
            log.error("异常信息:{}", e);
        }
        return null;
    }

    public static void delete(File file) {
        if (!file.exists()) return;
        if (file.isFile() || file.list() == null) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (File file1 : files) {
                delete(file1);
            }
            file.delete();
        }

    }

    @Override
    public IPage<ApiVO> getApiListByProductId(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(baseMapper.getApiListByProductId(page, api));
    }

    @Override
    public List<ApiVO> getListByProductId(Long productId) {
        return baseMapper.getListByProductId(productId);
    }

    @Override
    public IPage<ApiVO> getApiListByCaseId(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(baseMapper.getApiListByCaseId(page, api));
    }

    @Override
    public int selectApiCountById(String appCode) {
        return apiMapper.selectApiCountById(appCode);
    }

    @Override
    public IPage<AppApiViewVo> selectProApiList(IPage<AppApiViewVo> page, AppApiViewVo appApiViewVo) {
        return page.setRecords(apiMapper.selectProApiList(page, appApiViewVo));
    }

    @Override
    public IPage<ApiVO> getApiListByAppId(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(apiMapper.getApiListByAppId(page, api));
    }

    @Override
    public List<ApiVO> getListByIds(@NotEmpty List<Long> ids) {
        return apiMapper.getListByIds(ids);
    }

    @Override
    public ApiListVo selectByApiCode(String apiCode) {
        return apiMapper.selectByApiCode(apiCode);
    }

    @Override
    public ApiListVo selectApiVoById(Long apiId) {
        return apiMapper.selectApiVoById(apiId);
    }

    @Override
    public Boolean updateApiWithTransformProtocol(Api api) {
        return apiMapper.updateApiWithTransformProtocol(api);
    }

    /**
     * @param id
     * @return java.util.List<com.dhcc.bpm.modules.api.entity.Api>
     * @Description 根据渠道id查询接口
     * @Author sjm
     * @Date 11:28 2020/3/13 0013
     **/
    @Override
    public List<Api> selectApiByAppId(Long id) {
        return apiMapper.selectApiByAppId(id);
    }

    @Override
    public List<ApiVO> selectBySysNum(String apiNum) {
        return apiMapper.selectBySysNum(apiNum);
    }

    /**
     * @param page
     * @param api
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.api.vo.ApiVO>
     * @Description 某一api下回调地址列表
     * @Author Mdd
     * @Date 2020/4/10 15:12
     **/
    @Override
    public IPage<ApiVO> callBackList(IPage<ApiVO> page, ApiVO api) {
        return page.setRecords(apiMapper.callBackList(page, api));
    }

    @Override
    public int updateRefreshStatus(ApiVO api) {
        return apiMapper.updateRefreshStatus(api);
    }

    @Override
    public List<ListAllApisVO> listAllApis() {
        return apiMapper.listAllApis();
    }

    @Override
    public List<Api> getProdApiByProductId(Long productId) {
        return apiMapper.getProdApiByProductId(productId);
    }
    @Override
    public List<Long> getProdApiIdsByProductId(Long productId) {
        return apiMapper.getProdApiIdsByProductId(productId);
    }

    @Override
    public List<String> getApiBySysId(Long sysId) {
        return apiMapper.getApiBySysId(sysId);
    }

    @Override
    public List<Long> getApiIdsBySysId(String sysId) {
        return apiMapper.getApiIdsBySysId(sysId);
    }

    @Override
    public List<ApiVO> findApiByProductId(Long productId) {
        return apiMapper.findApiByProductId(productId);
    }

    @Override
    public IPage<ApiPageVO> selectPage(IPage<ApiPageVO> page, ApiVO api) {
        return page.setRecords(baseMapper.selectPage(page, api));
    }

}
